package com.keepers.repair.fragment

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.google.gson.Gson
import com.keepers.repair.R
import com.keepers.repair.adapter.SendResourceAdapter
import com.keepers.repair.model.FileHolderModel
import com.keepers.repair.model.XmlRootModel
import com.keepers.repair.utils.Api
import com.keepers.repair.utils.FileType
import com.keepers.repair.utils.GlideEngine
import com.keepers.repair.utils.encodeBase64Image
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.CaptureStrategy
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.design.snackbar
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.find
import org.jetbrains.anko.noButton
import org.jetbrains.anko.support.v4.alert
import org.jetbrains.anko.support.v4.indeterminateProgressDialog
import org.jetbrains.anko.support.v4.selector
import org.jetbrains.anko.support.v4.toast
import org.jetbrains.anko.yesButton
import pub.devrel.easypermissions.EasyPermissions
import retrofit2.adapter.rxjava2.Result
import java.util.*


class SendMessageFragment : Fragment(), EasyPermissions.PermissionCallbacks {

    private lateinit var recyclerView: RecyclerView
    private lateinit var sendButton: Button
    private lateinit var textView: TextView
    private var resourceList = mutableListOf<FileHolderModel>()
    private var repairId: String? = null
    private val imageRequestCode = 0x99
    private val videoRequestCode = 0x98
    private val permissionList = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_send_message, container, false)
        val recyclerLayoutManager = LinearLayoutManager(context)

//        repairId = (activity as SendActivity).repairId
        recyclerView = view.find(R.id.send_message_recycler_view)
        sendButton = view.find(R.id.send_message_button)
        textView = view.find(R.id.send_message_edit_text)

        recyclerLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        recyclerView.layoutManager = recyclerLayoutManager
        recyclerView.adapter = SendResourceAdapter(this, resourceList)

        sendButton.setOnClickListener { _ ->
            if (textView.text.isNullOrEmpty()) {
                alert("内容不能为空！") { yesButton {} }.show()
                return@setOnClickListener
            }
            alert("确定发送当前汇报？") {
                yesButton { send() }
                noButton {}
            }.show()
        }
        return view
    }

    fun addResource() {
        if (resourceList.size > 3) {
            this.view?.apply { snackbar(this, "文件数量超出限制") }
            return
        }
        if (! EasyPermissions.hasPermissions(context!!, *permissionList)) {
            EasyPermissions.requestPermissions(this, "使用上传功能需要您的授权，是否开启授权？",
                0, *permissionList)
        }
        val imageNumber = 4 - resourceList.size
        val menu = listOf("图片", "视频")
        selector("选择附件类型", menu) { _, position ->
            when (position) {
                0 -> {
                    Matisse.from(this@SendMessageFragment)
                        .choose(MimeType.ofImage())
                        .showSingleMediaType(true)
                        .capture(true)
                        .captureStrategy(CaptureStrategy(true, "com.keepers.repair.fileprovider"))
                        .maxSelectable(imageNumber)
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(GlideEngine())
                        .theme(R.style.Matisse_Dracula)
                        .forResult(imageRequestCode)
                }
                1 -> {
                    Matisse.from(this@SendMessageFragment)
                        .choose(MimeType.ofVideo())
                        .showSingleMediaType(true)
                        .maxSelectable(imageNumber)
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(GlideEngine())
                        .theme(R.style.Matisse_Dracula)
                        .forResult(videoRequestCode)
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        val fileType = when (requestCode) {
            imageRequestCode -> FileType.IMAGE
            videoRequestCode -> FileType.VIDEO
            else -> null
        }
        if (resultCode == Activity.RESULT_OK && fileType != null) {
            val selectors = Matisse.obtainResult(data)
            selectors.forEach { uri ->
                this.resourceList.add(FileHolderModel(uri, fileType))
            }
            this.recyclerView.adapter?.notifyDataSetChanged()
            return
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {}
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        this.alert(message = "无法获取授权") {
            isCancelable = false
        }.show()
    }

    private fun send() {
        val message = textView.text.toString()
        if (repairId.isNullOrEmpty()) {
            toast("当前维修单有误！")
            return
        }
        val pgsDialog = indeterminateProgressDialog(message = "正在上传...") {
            this.setCancelable(false)
        }
        pgsDialog.show()
        doAsync {
            val array: MutableList<Observable<Result<XmlRootModel>>> = resourceList.map { fileHolder ->
                val bitmap = BitmapFactory.decodeStream(context!!.contentResolver.openInputStream(fileHolder.uri))
                val str = encodeBase64Image(Bitmap.createScaledBitmap(bitmap, bitmap.width / 10, bitmap.height / 10, true))
                Api.clientService!!.repairUploadFiles(Date().time.toString(), fileHolder.fileType.value, repairId!!, str)
            } as MutableList<Observable<Result<XmlRootModel>>>
            array.add(Api.clientService!!.uploadOverhaulResult(repairId!!, message))
            Observable.zip(array) {list -> list}
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe { list ->
                    val results = list.map { item ->
                        val body: Any? = (item as Result<*>).response()?.body()
                        val content: String? = (body as XmlRootModel?)?.content
                        var value = false
                        content?.apply {
                            value = Gson().fromJson<kotlin.Boolean>(content, kotlin.Boolean::class.java)
                        }
                        value
                    }
                    if (results.all { element -> element }) {
                        toast("上传成功")
                        textView.text = ""
                        resourceList.clear()
                    } else {
                        toast("上传失败")
                    }
                    pgsDialog.hide()
                }
        }
    }
}
